const {LinValidator, Rule} = require('../../core/lin-validator')
const {User} = require('../models/user')
const {LoginType} = require('../lib/enum')

// 校验参数是正整数的类
class PositiveIntegerValidator extends LinValidator {
  constructor() {
      super()
      this.id = [
        new Rule('isInt', '需要是正整数', { min: 1 })
      ]
  }
}

// 注册的校验类
class RegisterValidator extends LinValidator {
  constructor() {
    super()
    this.email = [
      new Rule('isEmail', '邮箱格式不正确')
    ]
    this.password = [
      new Rule('isLength', '密码至少6个字符，最多32个字符', {
        min: 6,
        max: 32
      }),
      new Rule('matches', '密码格式不正确', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]')
    ]
    this.password2 = this.password
    this.nickname = [
      new Rule('isLength', '昵称不符合长度规范', {
        min: 6,
        max: 32
      }),
    ]
  }

  validatePassword(vals) {
    const psw1 = vals.body.password
    const psw2 = vals.body.password2
    if (psw1 !== psw2) {
      throw new Error('两次密码必须相同')
    }
  }
  async validateEmail(vals) {
    const email = vals.body.email
    const user = await User.findOne({
      where:{
        email
      }
    })
    if (user) {
      throw new Error('email已存在')
    }
  }
}

// token 的校验类

class TokenVlaidator extends LinValidator {
  constructor() {
    super()
    this.account = [
      new Rule('isLength', '不符合账户规则', {
        min: 4,
        max: 32
      })
    ]
    /* 
      密码可以空、不为空
      设置规则 --  isOptional  
    */
    this.secret = [
      new Rule('isOptional'),
      new Rule('isLength', '至少6个字符', {
        min: 6,
        max: 128
      })
    ]
  }

  validateLoginType(vals) {
    const type = vals.body.type
    if (!type) {
      throw new Error('type为必传参数')
    }
    if (!LoginType.isLoginType(type)) {
      throw new Error('type参数不正确')
    }
  }
}

module.exports = {
  PositiveIntegerValidator,
  RegisterValidator,
  TokenVlaidator
}
